const path = require("path");

const Koa = require("koa");
const koaBody = require("koa-body");
const KoaStatic = require("koa-static");
const parameter = require("koa-parameter");

const router = require("../router/index");
const errHandler = require("./errHandler");

const { defindKoaSwagger, swaggerSpec } = require("../swagger");

const app = new Koa();

module.exports = app;

// 执行 `npm run build` 遍历require让ncc建立依赖关系，但不执行代码
if (process.env.BUILD) return;

router.get(
  "/swagger",
  defindKoaSwagger({
    routePrefix: false,
    swaggerOptions: {
      spec: swaggerSpec,
    },
  })
);

app.use(
  koaBody({
    multipart: true,
    formidable: {
      // 指定上传文件夹路径，必须要用绝对路径
      uploadDir: path.join(__dirname, "../upload"),
      // 是否保存后缀名
      keepExtensions: true,
    },
  })
);

app.use(KoaStatic(path.join(__dirname, "../upload")));

// 必须放置router注册前
app.use(parameter(app));

// 统一注册Router, allowedMethods：设置请求方式不正确时提示
app.use(router.routes()).use(router.allowedMethods());

// 统一错误处理
app.on("error", errHandler);
